package com.villaday.idf.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import androidx.appcompat.widget.Toolbar;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.ApplyWithdrawlDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.AccountBalanceEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.Sms;
import com.villaday.idf.model.SmsEntity;
import com.villaday.idf.model.drawCash;
import com.villaday.idf.util.BigDecimalUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 收益提现
 */
public class CashWithdrawalActivity extends BaseActivity implements OkHttpUtil.OnDataListener, ApplyWithdrawlDialog.ApplyWithdrawlListener {
    @BindView(R.id.toolbar_text)
    public Toolbar toolbar;
    @BindView(R.id.tv_balance_note)
    public TextView tvBalanceNote;
    @BindView(R.id.et_withdrawal_balance)
    EditText etWithdrawalBalance;
    @BindView(R.id.et_real_name)
    EditText etRealName;
    @BindView(R.id.et_alipay_account)
    EditText etAlipayAccount;
    @BindView(R.id.et_input_msg_code)
    EditText etMsgCode;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;

    @BindView(R.id.tv_tips)
    TextView tvTips;

    @BindView(R.id.ll_flv)
    LinearLayout llFlv;

    @BindView(R.id.tv_fwf)
    TextView tvFwf;

    @BindView(R.id.tv_dzjine)
    TextView tvDzjine;


    private Handler handler = new Handler();

    private Gson gson = new GsonBuilder().create();
    private final int retryLimit = Constant.Integers.CodeRetryTime;//重试秒数上限
    private int timeNum = retryLimit;//获取验证码倒计时
    private String balance;
    private String realName;
    private String AlipayAccount;
    private LoadingDialog loadingDialog;
    private String CanWithdrawal;
    private RefreshtokenEntity refreshtoken;
    private ApplyWithdrawlDialog AWDialog;
    private AccountBalanceEntity mp;

    @Override
    protected int getViewResId() {
        return R.layout.activity_cash_withdrawal;
    }

    @Override
    protected void init() {
        tvGetCode.setSelected(true);
        ToolBarUtil.initToolBar(toolbar, "收益提现", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        }, "提现记录", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CashWithdrawalActivity.this, MyBalanceActivity.class));
            }
        });
        etWithdrawalBalance.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    llFlv.setVisibility(View.GONE);
                } else {
                    if (mp != null && mp.getBody() != null && !TextUtils.isEmpty(mp.getBody().getServiceRate())) {
                        llFlv.setVisibility(View.VISIBLE);
                        double rate = BigDecimalUtil.mul(Double.parseDouble(mp.getBody().getServiceRate()), Double.parseDouble("100")).doubleValue();
                        String[] split1 = (rate+"").split("\\.");

                        if (split1[1].length()==1){
                            tvFwf.setText("资金提现费率 " + split1[0]+"."+split1[1] +"0"+ "%");

                        }else {
                            tvFwf.setText("资金提现费率 " + split1[0]+"."+split1[1] + "%");

                        }
                        BigDecimal sub = BigDecimalUtil.div(BigDecimalUtil.sub(Double.parseDouble(s + ""), BigDecimalUtil.mul(Double.parseDouble(mp.getBody().getServiceRate()), Double.parseDouble(s + "")).doubleValue()).doubleValue(), 1.0, 4);
                        String[] split = sub.toString().split("\\.");
                        String sdje = split[0] + "." + split[1].substring(0, 2);
                        tvDzjine.setText(Html.fromHtml("实到账金额 &yen;" + sdje));
                    }


                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void loadData() {
        //已废弃
        /*Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, Constant.URL.member_profits, map, this);*/

        Map<String, Object> map2 = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.refresh_token, null, map2, this);
        //查询账户金额
        Map<String, String> map = new HashMap<>();
        map.put("type", "withdraw");
        OkHttpUtil.getJSON(this, Constant.URL.accountAmount, map, this);


    }

    @OnClick({R.id.tv_get_code, R.id.tv_Apply_withdrawl})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_get_code: { //获取验证码
                getCode();
                break;
            }

            case R.id.tv_Apply_withdrawl: { //申请提款
                balance = etWithdrawalBalance.getText().toString().trim();
                realName = etRealName.getText().toString().trim();
                AlipayAccount = etAlipayAccount.getText().toString().trim();
                if (balance.length() == 0) {
                    ToastUtil.initToast(this, "请输入提现金额");
                } else if (Double.parseDouble(balance) > Double.parseDouble(CanWithdrawal)) {
                    ToastUtil.initToast(this, "可提现金额不足");
                } else if (Double.parseDouble(balance) < 50) {
                    ToastUtil.initToast(this, "提现金额不低于50");
                } else if (realName.length() == 0) {
                    ToastUtil.initToast(this, "请输入真实姓名");
                } else if (AlipayAccount.length() == 0) {
                    ToastUtil.initToast(this, "请输入支付宝账号");
                } else if (etMsgCode.getText().toString().trim().length() == 0) {
                    ToastUtil.initToast(this, "请输入短信验证码");
                } else {
                    loadingDialog = LoadingDialog.newInstance("提现中...");
                    loadingDialog.show(getFragmentManager());
                    Map<String, Object> map = new HashMap<>();
                    OkHttpUtil.postJson(this, Constant.URL.draw_cash, new drawCash(Integer.parseInt(balance) * 100, etMsgCode.getText().toString().trim(), realName, AlipayAccount), map, this);
                }
                break;
            }
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.accountAmount.equals(url)) { //收益统计
                LogeUtil.e("accountAmount", json);
                mp = gson.fromJson(json, AccountBalanceEntity.class);
                if (Constant.Strings.SUC.equals(mp.getCode())) {
                   /* CanWithdrawal = mp.getBody().getUnfrozen();
                    tvBalanceNote.setText("您的余额：¥" +mp.getBody().getBalanceValue() + ",最高可提现：¥" + mp.getBody().getUnfrozenValue());
                */
                    tvBalanceNote.setText(mp.getBody().getAlertTips());

                    CanWithdrawal = mp.getBody().getAvailableAmount();
                    tvTips.setText(mp.getBody().getTips());
                } else {
                    ToastUtil.initToast(this, mp.getMsg());
                }
            } else if (Constant.URL.draw_cash.equals(url)) {
                LogeUtil.e("draw_cash", json);
                dismissLoading();
                SmsEntity se = gson.fromJson(json, SmsEntity.class);
                if (Constant.Strings.SUC.equals(se.getCode())) {
                    String content = getResources().getString(R.string.applyWithdrawl);
                    LogeUtil.e("loge", "content===" + content);
                    AWDialog = ApplyWithdrawlDialog.newInstance(CashWithdrawalActivity.this, "申请已提交", content, "我知道了");
                    AWDialog.setListener(this);
                    AWDialog.show(getFragmentManager());
                } else {
                    ToastUtil.initToast(this, se.getMsg());
                }
            } else if (Constant.URL.refresh_token.equals(url)) { //刷新Token
                LogeUtil.e("refresh_token", json);
                refreshtoken = gson.fromJson(json, RefreshtokenEntity.class);
                if (Constant.Strings.SUC.equals(refreshtoken.getCode())) {
                    //改变 主页bottom vip 图标及文字颜色
                    mRxManager.post(getResources().getString(R.string.ChangeMainBotton_vip_dirwableAndColor), refreshtoken.getBody().getMember().getType());

                    SharedPreferencesUtil.saveRoleInfo(this, json);
                    SharedPreferencesUtil.saveToken(this, refreshtoken.getBody().getToken());
                    UpdateUI(refreshtoken.getBody().getMember());
                } else {
                    ToastUtil.initToast(this, refreshtoken.getMsg());
                }
            } else if (Constant.URL.sms.equals(url)) {
                LogeUtil.e("sms", json);
            }

        }
    }

    @Override
    public void onFailure(String url, String error) {

    }

    private void UpdateUI(RefreshtokenEntity.BodyBean.MemberBean mb) {
        if (mb != null) {
           /* if (TextUtils.isEmpty(mb.getZfb()) && TextUtils.isEmpty(mb.getName())) {
                etRealName.setEnabled(true);
                etAlipayAccount.setEnabled(true);
            } else {*/
                /*etRealName.setEnabled(false);
                etAlipayAccount.setEnabled(false);*/
            etAlipayAccount.setText(mb.getZfb());
            etRealName.setText(mb.getName());
            //}
        }
    }


    private void getCode() {
        balance = etWithdrawalBalance.getText().toString().trim();
        realName = etRealName.getText().toString().trim();
        AlipayAccount = etAlipayAccount.getText().toString().trim();
        if (tvGetCode.isSelected()) {
            if (balance.length() == 0) {
                ToastUtil.initToast(this, "请输入提现金额");
            } else if (Double.parseDouble(balance) < 50) {
                ToastUtil.initToast(this, "提现金额不低于50");
            } else if (realName.length() == 0) {
                ToastUtil.initToast(this, "请输入真实姓名");
            } else if (AlipayAccount.length() == 0) {
                ToastUtil.initToast(this, "请输入支付宝账号");
            } else {
                tvGetCode.setSelected(false);
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(this, Constant.URL.sms, new Sms(403, SharedPreferencesUtil.getRoleInfo(this).getMember().getMobile()), map, this);
                //设置XX秒后重试
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (tvGetCode != null) {
                            tvGetCode.setText("点击重新发送 (" + timeNum + ")");
                            if (timeNum > 0) {
                                handler.postDelayed(this, 1000);
                                timeNum--;
                            } else {
                                tvGetCode.setText("发送验证码");
                                timeNum = retryLimit;
                                tvGetCode.setSelected(true);
                            }
                        }
                    }
                });
            }
        }
    }

    private void upTimeNum() {
        if (timeNum < retryLimit) {//倒计时中
            timeNum = 0;
        }
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }


    public void refresh() {

    }

    @Override
    public void finishApplyWithdraw() {
        setResult(RESULT_OK);
        finish();
    }
}
